﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Bilibili.Model.Channel;
using Bilibili.Model.Resource;
using Bilibili.Common;
using Bilibili.Common.Log;
using PCLUntils.Objects;
using PCLUntils.Json;

namespace Bilibili.WebClient.Api
{
    public sealed class ChannelClient : ClientBase
    {
        public async Task<ReturnModel<ReturnJObject>> GetRank(int rid, string type)
        {
            try
            {
                ApiInfo apiInfo = new ApiInfo("https://api.bilibili.com/x/web-interface/ranking/v2", $"&rid={rid}&type={type.ToLower()}", false);
                string results = await ApiClient.GetResults(apiInfo);
                var model = results.ParseObject<ReturnJObject>();
                return BuildSuccessResult(model);
            }
            catch (Exception ex)
            {
                LogManager.Instance.LogError("GetRank", ex);
                return BuildExceptionResult<ReturnJObject>(ex);
            }
        }
        public async Task<ReturnModel<RegionModel>> SetRegions()
        {
            try
            {
                ApiInfo apiInfo = new ApiInfo("https://app.bilibili.com/x/v2/region/index", false);
                string results = await ApiClient.GetResults(apiInfo);
                var model = results.ParseObject<RegionModel>();
                if (model.IsNotEmpty())
                {
                    model.Data.RemoveAll(x => x.Name == "会员购" || x.Name == "音频" || x.Name == "原创排行榜" || x.Logo == "");
                    return BuildSuccessResult(model);
                }
                else
                    return BuildFailedResult<RegionModel>();
            }
            catch (Exception ex)
            {
                LogManager.Instance.LogError("SetRegions", ex);
                return BuildExceptionResult<RegionModel>(ex);
            }
        }
        public async Task<ReturnModel<List<ChannelFeed>>> GetChannelFeeds(string channel_id, string name, int page)
        {
            ApiInfo apiInfo = new ApiInfo("https://app.bilibili.com/x/channel/feed", $"&channel_id={channel_id}&channel_name={Uri.EscapeDataString(name)}&display_id={page}&login_event=0&pull={(page == 1).ToString().ToLower()}", true);
            var results = await ApiClient.GetResults(apiInfo);
            var model = results.ToDynamicJObject();
            if (model.IsNotEmpty())
            {
                if (model.Code == 0)
                {
                    var m = model.Json["data"].ToObject<ChannelFeedRoot>();
                    return BuildSuccessResult(m.Feed);
                }
                else
                    return BuildFailedResult<List<ChannelFeed>>(model.Message);
            }
            else
                return BuildFailedResult<List<ChannelFeed>>();
        }
    }
}